import { useCallback, useMemo } from 'react';
import { useHistory, useLocation, useParams } from 'react-router-dom';
import { isObject } from 'lodash';
import qs from 'qs';

export default function useRouter() {
  const history = useHistory();
  const location = useLocation();
  const params = useParams();

  const query = useMemo(() => {
    return qs.parse(location.search, { ignoreQueryPrefix: true });
  }, [location]);

  const push = useCallback((to) => {
    if (isObject(to)) {
      history.push({
        pathname: to.path,
        search: qs.stringify(to.query)
      });
    } else {
      history.push(to);
    }
  }, [history]);

  return {
    history,
    location,
    params,
    query,
    push
  };
}
